/*
 * @lc app=leetcode.cn id=2 lang=swift
 *
 * [2] 两数相加
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public var val: Int
 *     public var next: ListNode?
 *     public init() { self.val = 0; self.next = nil; }
 *     public init(_ val: Int) { self.val = val; self.next = nil; }
 *     public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; }
 * }
 */
class Solution {
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {

        var l1 = l1
        var l2 = l2

        var root = ListNode(0)
        var cursor: ListNode? = root
        var base = 0

        while l1 != nil || l2 != nil || base > 0 {
            let val1 = l1?.val ?? 0
            let val2 = l2?.val ?? 0
            let sum = val1 + val2 + base
            base = sum / 10

            let curNode = ListNode(sum % 10)
            cursor?.next = curNode
            cursor = cursor?.next

            l1 = l1?.next
            l2 = l2?.next
        }

        return root.next
    }
}
// @lc code=end

